package com.chaos.auth.config;

import com.chaos.auth.config.grant.converter.AdminPasswordAuthenticationConverter;
import com.chaos.auth.config.grant.converter.AdminPhoneAuthenticationConverter;
import com.chaos.auth.config.grant.converter.AppOpenIdAuthenticationConverter;
import com.chaos.auth.config.grant.converter.helper.OAuth2EndpointHelper;
import com.chaos.auth.config.grant.provider.AdminPasswordAuthenticationProvider;
import com.chaos.auth.config.grant.provider.AdminPhoneAuthenticationProvider;
import com.chaos.auth.config.grant.provider.AppOpenIdAuthenticationProvider;
import com.chaos.auth.config.grant.provider.RefreshTokenAuthenticationProvider;
import com.chaos.auth.config.handler.AuthenticationSuccessHandler;
import com.chaos.auth.config.mixin.SecurityUserMixin;
import com.chaos.auth.config.userdetails.details.AdminUserDetails;
import com.chaos.auth.config.userdetails.details.AppUserDetails;
import com.chaos.auth.config.userdetails.service.AdminByPhoneDetailsService;
import com.chaos.auth.config.userdetails.service.AdminByUsernameDetailsService;
import com.chaos.auth.config.userdetails.service.AppByWxOpenIdDetailsService;
import com.chaos.framework.model.enums.ResultEnum;
import com.chaos.framework.model.serivce.RedisService;
import com.chaos.system.api.data.RbacUserData;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationProvider;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceCodeAuthenticationProvider;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2RefreshTokenAuthenticationProvider;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.token.DelegatingOAuth2TokenGenerator;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.token.JwtGenerator;
import org.springframework.security.oauth2.server.authorization.token.OAuth2AccessTokenGenerator;
import org.springframework.security.oauth2.server.authorization.token.OAuth2RefreshTokenGenerator;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.security.oauth2.server.authorization.web.authentication.DelegatingAuthenticationConverter;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@EnableWebSecurity
@Configuration
public class SecurityConfig {
    @Autowired
    private AdminByUsernameDetailsService adminByUsernameDetailsService;
    @Autowired
    private AdminByPhoneDetailsService adminByPhoneDetailsService;
    @Autowired
    private AppByWxOpenIdDetailsService appByWxOpenIdDetailsService;
    @Autowired
    private JdbcOperations jdbcOperations;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;

    @Value("${keystore.path}")
    private String keystorePath;

    @Value("${keystore.password}")
    private String keystorePassword;

    @Value("${keystore.alias}")
    private String keystoreAlias;


    @Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {

        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class).oidc(Customizer.withDefaults())
                .tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(customConverter()).authenticationProviders(this::customProvider)
                        .accessTokenResponseHandler(new AuthenticationSuccessHandler(new ObjectMapper())).errorResponseHandler((request, response, exception) -> {
                            response.setContentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8");
                            response.setCharacterEncoding("UTF-8");
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            ObjectMapper mapper = new ObjectMapper();
                            OAuth2AuthenticationException error = (OAuth2AuthenticationException) exception;
                            OAuth2Error e = error.getError();
                            Map map = Map.of("code", e.getErrorCode(), "msg", e.getDescription());
                            String json = mapper.writeValueAsString(map);
                            response.getWriter().write(json);
                        }));

        http.exceptionHandling((exceptions) -> exceptions.defaultAuthenticationEntryPointFor((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED), new MediaTypeRequestMatcher(MediaType.APPLICATION_JSON)

        ));
        return http.build();
    }


    @Bean
    @Order(2)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll()).formLogin(form -> form.disable()).httpBasic(basic -> basic.disable());
        http.csrf(csrf -> csrf.disable());

        return http.build();
    }

    @Bean
    public OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator() {
        NimbusJwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSource());
        JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
        jwtGenerator.setJwtCustomizer(tokenCustomizer());
        OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
        OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
        return new DelegatingOAuth2TokenGenerator(jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
    }

    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
        return context -> {
            Authentication principal = context.getPrincipal();
            if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
                Set<String> authorities = principal.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
                context.getClaims().claim("authorities", authorities);
                if (principal.getPrincipal() instanceof AppUserDetails) {
                    AppUserDetails user = (AppUserDetails) principal.getPrincipal();
                    context.getClaims().claim("userId", user.getUserId());

                    Long userInfoId = user.getUserInfoId();
                    if (userInfoId != null) {
                        context.getClaims().claim("userInfoId", userInfoId);
                    }
                }
                else if (principal.getPrincipal() instanceof AdminUserDetails) {
                    AdminUserDetails admin = (AdminUserDetails) principal.getPrincipal();
                    context.getClaims().claim("adminId", admin.getUser().getId());
                }
                else {
                    OAuth2EndpointHelper.throwError(ResultEnum.UNSUPPORTED_USER_DETAILS);
                }


            }


        };
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }


    @Bean
    public JWKSource<SecurityContext> jwkSource() {
        KeyPair keyPair = generateRsaKey();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAKey rsaKey = new RSAKey.Builder(publicKey).privateKey(privateKey).keyID(UUID.randomUUID().toString()).build();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return new ImmutableJWKSet<>(jwkSet);
    }


    public KeyPair generateRsaKey() {
        Resource resource;
        if (keystorePath.startsWith("classpath:")) {
            resource = new ClassPathResource(keystorePath.substring("classpath:".length()));
        }
        else {
            resource = new FileSystemResource(keystorePath);
        }
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(resource, keystorePassword.toCharArray());
        KeyPair keyPair = factory.getKeyPair(keystoreAlias, keystorePassword.toCharArray());
        return keyPair;
    }

    @Bean
    public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
        return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
    }

    @Bean
    public AuthorizationServerSettings authorizationServerSettings() {
        return AuthorizationServerSettings.builder().build();
    }

    @Bean
    public RegisteredClientRepository registeredClientRepository() {
        return new JdbcRegisteredClientRepository(jdbcTemplate);
    }


    @Bean
    public OAuth2AuthorizationService oAuth2AuthorizationService() {
        RegisteredClientRepository registeredClientRepository = registeredClientRepository();
        JdbcOAuth2AuthorizationService jdbcOAuth2AuthorizationService = new JdbcOAuth2AuthorizationService(jdbcOperations, registeredClientRepository);
        JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper authorizationRowMapper = new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper(registeredClientRepository);
        ObjectMapper objectMapper = new ObjectMapper();
        ClassLoader classLoader = JdbcOAuth2AuthorizationService.class.getClassLoader();
        List<Module> securityModules = SecurityJackson2Modules.getModules(classLoader);
        objectMapper.registerModules(securityModules);
        objectMapper.registerModule(new OAuth2AuthorizationServerJackson2Module());
        objectMapper.addMixIn(RbacUserData.class, SecurityUserMixin.class);
        objectMapper.addMixIn(AppUserDetails.class, SecurityUserMixin.class);
        authorizationRowMapper.setObjectMapper(objectMapper);
        authorizationRowMapper.setLobHandler(new DefaultLobHandler());
        jdbcOAuth2AuthorizationService.setAuthorizationRowMapper(authorizationRowMapper);
        return jdbcOAuth2AuthorizationService;
    }

    @Bean
    public OAuth2AuthorizationConsentService authorizationConsentService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
        return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository);
    }

    //增加自定义模式：Converter，Provider

    private DelegatingAuthenticationConverter customConverter() {


        //默认支持：客户端模式，refresh，授权码模式(暂不能正常使用、不提供)

        //密码模式
        AdminPasswordAuthenticationConverter adminPassword = new AdminPasswordAuthenticationConverter();
        AdminPhoneAuthenticationConverter adminPhone = new AdminPhoneAuthenticationConverter();

        //openid
        AppOpenIdAuthenticationConverter appOpenId = new AppOpenIdAuthenticationConverter();

        return new DelegatingAuthenticationConverter(Arrays.asList(adminPassword, adminPhone, appOpenId));

    }

    /**
     * 添加自定义认证提供者
     */
    private void customProvider(List<AuthenticationProvider> customProviders) {
        customProviders.removeIf(provider -> provider instanceof OAuth2AuthorizationCodeAuthenticationProvider || provider instanceof OAuth2RefreshTokenAuthenticationProvider || provider instanceof OAuth2DeviceCodeAuthenticationProvider);

        //授权码模式（暂不可用）
        //customProviders.add(daoAuthenticationProvider());

        // refresh
        customProviders.add(refreshTokenAuthenticationProvider());
        // adminPassword
        customProviders.add(adminPasswordAuthenticationProvider());
        // appOpenid
        customProviders.add(appOpenIdAuthenticationProvider());
        // adminPhone
        customProviders.add(adminPhoneAuthenticationProvider());


    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(adminByUsernameDetailsService);
        provider.setPasswordEncoder(passwordEncoder());
        return provider;
    }

    @Bean
    public RefreshTokenAuthenticationProvider refreshTokenAuthenticationProvider() {
        RefreshTokenAuthenticationProvider provider = new RefreshTokenAuthenticationProvider(oAuth2AuthorizationService(), tokenGenerator());

        return provider;
    }

    @Bean
    public AdminPasswordAuthenticationProvider adminPasswordAuthenticationProvider() {
        AdminPasswordAuthenticationProvider provider = new AdminPasswordAuthenticationProvider();
        provider.setUserDetailsService(adminByUsernameDetailsService);
        provider.setPasswordEncoder(passwordEncoder());
        provider.setAuthorizationService(oAuth2AuthorizationService());
        provider.setTokenGenerator(tokenGenerator());
        return provider;
    }

    @Bean
    public AdminPhoneAuthenticationProvider adminPhoneAuthenticationProvider() {
        AdminPhoneAuthenticationProvider provider = new AdminPhoneAuthenticationProvider();
        provider.setUserDetailsService(adminByPhoneDetailsService);
        provider.setAuthorizationService(oAuth2AuthorizationService());
        provider.setTokenGenerator(tokenGenerator());
        provider.setRedisService(redisService);
        return provider;
    }


    @Bean
    public AppOpenIdAuthenticationProvider appOpenIdAuthenticationProvider() {
        AppOpenIdAuthenticationProvider provider = new AppOpenIdAuthenticationProvider();
        provider.setAppByWxOpenIdDetailsService(appByWxOpenIdDetailsService);
        provider.setAuthorizationService(oAuth2AuthorizationService());
        provider.setTokenGenerator(tokenGenerator());
        return provider;
    }


    //    授权码模式（无效）
    //    @Bean
    //    public AdminCodeAuthenticationProvider adminCodeAuthenticationProvider() {
    //        AdminCodeAuthenticationProvider provider = new AdminCodeAuthenticationProvider();
    //        provider.setUserDetailsService(adminByUsernameDetailsService);
    //        provider.setPasswordEncoder(passwordEncoder());
    //        return provider;
    //    }

}
